package com.example.timetable.fragment;

import static android.content.Context.MODE_PRIVATE;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.timetable.R;
import com.example.timetable.dao.Course;
import com.example.timetable.databinding.FragmentTableBinding;
import com.example.timetable.dialog.DateEditDialog;
import com.google.android.material.snackbar.Snackbar;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 课表的碎片
 */
public class TableFragment extends Fragment {

    private FragmentTableBinding binding;
    private SharedPreferences sp;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentTableBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        //初始化轻量级存储 SharedPreferences
        sp = getContext().getSharedPreferences("config", MODE_PRIVATE);
        //获取开学时间戳用来定位今天是第几周
        long date = sp.getLong("date",System.currentTimeMillis());
        //将数据放入课表中
        binding.timeTable.loadData(acquireData(), new Date(date));
    }

    private List<Course> acquireData() {
        List<Course> courses = new ArrayList<>();
        //判断是否首次使用，如果首次使用sp找不到这个字段，isFirstUse未默认值true
        if (sp.getBoolean("isFirstUse", true)) {
            //标记未非首次打开应用
            sp.edit().putBoolean("isFirstUse", false).apply();
            //弹出修改开学时间的窗口
            DateEditDialog.alterDate(getContext(),sp);
        }else {
            //用LitePal查询SQLite数据库中课程数据
            courses = LitePal.findAll(Course.class);
        }
        return courses;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}